<template>
  <div class="index-manager-container" v-loading="loading" element-loading-text="正在加载...">
    <h1 class="page-title">首页管理</h1>

    <!-- 首页标题和Banner设置 -->
    <el-row :gutter="20" class="top-settings">
      <!-- 首页标题设置 -->
      <el-col :span="12">
        <el-card class="setting-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>首页标题设置</span>
            </div>
          </template>
          <el-form :model="homeSettings" label-width="100px">
            <el-form-item label="页面标题">
              <el-input v-model="homeSettings.title" placeholder="请输入首页标题" maxlength="50" show-word-limit />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 首页Banner设置 -->
      <el-col :span="12">
        <el-card class="setting-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>首页Banner设置</span>
            </div>
          </template>
          <el-form :model="homeSettings" label-width="100px">
            <el-form-item label="Banner图片">
              <div class="banner-upload">
                <el-upload
                  class="banner-uploader"
                  action="#"
                  :show-file-list="false"
                  :on-change="handleBannerUpload"
                  :auto-upload="false"
                  accept="image/*"
                >
                  <img v-if="homeSettings.bannerUrl" :src="homeSettings.bannerUrl" class="banner-preview" />
                  <div v-else class="banner-placeholder">
                    <el-icon class="upload-icon"><Plus /></el-icon>
                    <div class="upload-text">点击上传Banner图片</div>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 热门栏目设置 -->
    <el-card class="setting-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>热门栏目设置</span>
          <div class="card-tip">
            <small>配置首页热门栏目，支持图片展示和跳转功能。完整配置需要上传图片、选择跳转类型和目标内容。</small>
          </div>
        </div>
      </template>
      <div class="hot-sections">
        <div v-for="(item, index) in hotSections" :key="index" class="hot-section-item">
          <div class="section-header">
            <span class="section-title">栏目 {{ index + 1 }}</span>
          </div>
          <el-form :model="item" label-width="100px" class="section-form">
            <el-form-item label="背景图片">
              <div class="image-upload">
                <el-upload
                  class="image-uploader"
                  action="#"
                  :show-file-list="false"
                  :on-change="(file) => handleImageUpload(file, index)"
                  :auto-upload="false"
                  accept="image/*"
                >
                  <img v-if="item.imageUrl" :src="item.imageUrl" class="image-preview" />
                  <div v-else class="image-placeholder">
                    <el-icon class="upload-icon"><Plus /></el-icon>
                    <div class="upload-text">上传图片</div>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item label="跳转目标">
              <el-select 
                v-model="item.targetType" 
                placeholder="请选择跳转类型" 
                class="target-select"
                @change="() => item.targetValue = ''"
              >
                <el-option label="服务站点分类" value="category" />
                <el-option label="服务菜单名称" value="service" />
              </el-select>
            </el-form-item>
            <el-form-item label="目标内容" v-if="item.targetType">
              <el-select 
                v-model="item.targetValue" 
                :placeholder="item.targetType === 'category' ? '请选择分类' : '请选择服务菜单'"
                class="target-select"
                filterable
              >
                <el-option 
                  v-for="option in getTargetOptions(item.targetType)"
                  :key="option.id || option.value"
                  :label="option.name || option.label"
                  :value="option.name || option.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button 
        type="primary" 
        size="large" 
        @click="saveSettings"
        :loading="loading"
      >
        <el-icon><Check /></el-icon>
        保存设置
      </el-button>
      <el-button 
        size="large" 
        @click="resetSettings"
        :disabled="loading"
      >
        <el-icon><RefreshLeft /></el-icon>
        重置
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { Plus, Check, RefreshLeft } from '@element-plus/icons-vue'
import { homeAPI, categoryAPI, menuAPI, uploadAPI } from '@/api'

// 首页设置数据
const homeSettings = reactive({
  title: '人才地图管理系统',
  bannerUrl: '',
})

// 热门栏目数据
const hotSections = ref([
  {
    imageUrl: '',
    targetType: '',
    targetValue: '',
  },
  {
    imageUrl: '',
    targetType: '',
    targetValue: '',
  },
  {
    imageUrl: '',
    targetType: '',
    targetValue: '',
  },
])

// 分类选项和菜单选项
const categoryOptions = ref([])
const menuOptions = ref([])
const loading = ref(false)

// 处理Banner图片上传
const handleBannerUpload = async (file) => {
  try {
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在上传图片...',
    })

    const response = await uploadAPI.uploadFile(file.raw, 'banner')
    if (response.code === 200) {
      homeSettings.bannerUrl = response.data.url
      ElMessage.success('Banner图片上传成功')
    } else {
      ElMessage.error(response.message || '上传失败')
    }
    
    loadingInstance.close()
  } catch (error) {
    console.error('Banner上传失败:', error)
    ElMessage.error('上传失败，请重试')
  }
}

// 处理栏目图片上传
const handleImageUpload = async (file, index) => {
  try {
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在上传图片...',
    })

    const response = await uploadAPI.uploadFile(file.raw, 'section')
    if (response.code === 200) {
      hotSections.value[index].imageUrl = response.data.url
      ElMessage.success('栏目图片上传成功')
    } else {
      ElMessage.error(response.message || '上传失败')
    }
    
    loadingInstance.close()
  } catch (error) {
    console.error('栏目图片上传失败:', error)
    ElMessage.error('上传失败，请重试')
  }
}

// 保存设置
const saveSettings = async () => {
  // 验证数据
  if (!homeSettings.title.trim()) {
    ElMessage.warning('请输入首页标题')
    return
  }

  // 验证热门栏目配置
  const validSections = hotSections.value.filter(item => 
    item.imageUrl || item.targetType || item.targetValue
  )
  
  for (const section of validSections) {
    if (section.imageUrl && section.targetType && !section.targetValue) {
      ElMessage.warning('请完善热门栏目的目标内容配置')
      return
    }
    if (section.imageUrl && !section.targetType) {
      ElMessage.warning('请选择热门栏目的跳转目标类型')
      return
    }
  }

  try {
    loading.value = true
    
    // 构建保存数据
    const saveData = {
      title: homeSettings.title,
      bannerUrl: homeSettings.bannerUrl,
      hotSections: hotSections.value.filter(item => 
        item.imageUrl && item.targetType && item.targetValue
      )
    }

    const response = await homeAPI.saveHomeSettings(saveData)
    
    if (response.code === 200) {
      ElMessage.success('保存成功！')
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存首页设置失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重置设置
const resetSettings = () => {
  homeSettings.title = '人才地图管理系统'
  homeSettings.bannerUrl = ''

  hotSections.value.forEach((item) => {
    item.imageUrl = ''
    item.targetType = ''
    item.targetValue = ''
  })

  ElMessage.info('已重置为默认设置')
}

// 加载分类和菜单选项
const loadOptions = async () => {
  try {
    // 获取service类型的分类
    const categoryResponse = await categoryAPI.getList('service')
    if (categoryResponse.code === 200) {
      categoryOptions.value = categoryResponse.data || []
    }

    // 获取顶级服务菜单
    const menuResponse = await menuAPI.getTopMenu()
    if (menuResponse.code === 200) {
      menuOptions.value = menuResponse.data || []
    }
  } catch (error) {
    console.error('加载选项数据失败:', error)
  }
}

// 页面加载时获取已保存的设置
onMounted(() => {
  loadSettings()
  loadOptions()
})

// 加载已保存的设置
const loadSettings = async () => {
  try {
    loading.value = true
    const response = await homeAPI.getHomeSettings()
    
    if (response.code === 200 && response.data) {
      const data = response.data
      
      // 更新首页设置
      if (data.title) homeSettings.title = data.title
      if (data.bannerUrl) homeSettings.bannerUrl = data.bannerUrl
      
      // 更新热门栏目设置
      if (data.hotSections && Array.isArray(data.hotSections)) {
        data.hotSections.forEach((section, index) => {
          if (index < hotSections.value.length) {
            hotSections.value[index] = { ...section }
          }
        })
      }
    }
  } catch (error) {
    console.error('加载首页设置失败:', error)
    // 不显示错误消息，使用默认设置
  } finally {
    loading.value = false
  }
}

// 获取目标选项列表
const getTargetOptions = (targetType) => {
  if (targetType === 'category') {
    return categoryOptions.value
  } else if (targetType === 'service') {
    return menuOptions.value
  }
  return []
}
</script>

<style scoped>
.index-manager-container {
  padding: 20px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  height: 100%;
  overflow-y: auto;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.setting-card {
  margin-bottom: 20px;
  border-radius: 8px;
  height: 100%;
}

.top-settings {
  margin-bottom: 20px;
}

.top-settings .el-col {
  display: flex;
}

.top-settings .setting-card {
  margin-bottom: 0;
  flex: 1;
}

.card-header {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.card-tip {
  margin-top: 4px;
}

.card-tip small {
  color: #909399;
  font-weight: normal;
  font-size: 12px;
  line-height: 1.4;
}

/* Banner上传样式 */
.banner-upload {
  width: 100%;
}

.banner-uploader {
  width: 100%;
}

.banner-preview {
  width: 100%;
  max-width: 300px;
  height: 90px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
}

.banner-placeholder {
  width: 100%;
  max-width: 300px;
  height: 90px;
  border: 2px dashed #d3dce6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
  background-color: #fafafa;
}

.banner-placeholder:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 24px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
}

/* 热门栏目样式 */
.hot-sections {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.hot-section-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  background-color: #fff;
}

.section-header {
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f2f5;
}

.section-title {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.section-form {
  margin: 0;
}

.section-form .el-form-item {
  margin-bottom: 16px;
}

.target-select {
  width: 100%;
}

/* 栏目图片上传样式 */
.image-upload {
  width: 100%;
}

.image-uploader {
  width: 100%;
}

.image-preview {
  width: 85px;
  height: 85px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.image-placeholder {
  width: 85px;
  height: 85px;
  border: 2px dashed #d3dce6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
  background-color: #fafafa;
}

.image-placeholder:hover {
  border-color: #409eff;
}

.image-placeholder .upload-icon {
  font-size: 18px;
  margin-bottom: 4px;
}

.image-placeholder .upload-text {
  font-size: 12px;
}

/* 操作按钮样式 */
.action-buttons {
  text-align: center;
  margin-top: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
}

.action-buttons .el-button {
  margin: 0 10px;
  min-width: 120px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .top-settings .el-col {
    margin-bottom: 20px;
  }
  
  .top-settings .el-col:last-child {
    margin-bottom: 0;
  }
  
  .hot-sections {
    grid-template-columns: 1fr;
  }

  .banner-preview,
  .banner-placeholder {
    width: 100%;
    max-width: 400px;
  }

  .action-buttons .el-button {
    margin: 5px;
    width: 100%;
    max-width: 200px;
  }
}

/* Element Plus 组件样式调整 */
:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  color: #606266;
  font-weight: 500;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>
